<?php
class ResponseXSL extends DOMDocument 
{
	public $header = 'Content-Type: application/xml;';
	
	/**
	 * XSL response
	 *
	 * @param string $name object name
	 * @param array $output output settings for XSLT
	 */
	public function __construct($name, $outputs = array())
	{
		$file = PATH2TEMPLATES.$name.'.xsl';
		
		if (file_exists($file)) {
			$this->loadXML(file_get_contents($file));
			
			if (!is_null(DataObject::$system['language'])) {
				foreach (Localization::getData($name) as $name_k => $name_v) {
					$variable = $this->createElementNS('http://www.w3.org/1999/XSL/Transform', 'xsl:variable');
					$variable = $this->childNodes->item(0)->insertBefore($variable, $this->firstChild->firstChild);
					$variable->setAttribute('name', 'lang.'.$name_k);
					
					foreach ($name_v as $lang_k => $lang_v) {
						$if = $this->createElementNS('http://www.w3.org/1999/XSL/Transform', 'xsl:if');
						$if = $variable->insertBefore($if, $this->firstChild->firstChild->firstChild);
						$if->setAttribute('test', '$lang = \''.$lang_k.'\'');
						$if->appendChild(new DOMText($lang_v));
					}
				}
				
				$language = $this->createElementNS('http://www.w3.org/1999/XSL/Transform', 'xsl:variable');
				$language = $this->childNodes->item(0)->insertBefore($language, $this->firstChild->firstChild);
				$language->setAttribute('name', 'lang');
				$language->setAttribute('select', '//system/language');
			}
			
			if (count($outputs)) {
				$output = $this->createElementNS('http://www.w3.org/1999/XSL/Transform', 'xsl:output');
				$output = $this->childNodes->item(0)->insertBefore($output, $this->firstChild->firstChild);
				
				foreach ($outputs as $k => $v) {
					$output->setAttribute($k, $v);
				}
			}
		} else {
			$this->loadXML('<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"></xsl:template></xsl:stylesheet>');
		}
	}
	
	public function __toString()
	{
		return $this->saveXML();
	}
}
?>